import json
import re

from django.core.cache import cache
from django.http import JsonResponse
from django.views import View
from django.shortcuts import render
from areas.models import Area
import logging
logger = logging.getLogger('django')

# Create your views here.

from users.models import Address

# 查省份
class ProvinceAreasView(View):
    """省级地区"""
    def get(self, request):
        # 增加判断缓存
        province_list = cache.get('province_list')
        if not province_list:
            try:
                # 1.查询省级数据
                province_model_list = Area.objects.filter(parent__isnull=True)
                # 2.整理省级数据
                province_list = [{'id':i.id,'name':i.name} for i in province_model_list]
            except Exception as e:
                return JsonResponse({'code':400,
                                     'errmsg':'省份数据错误'})
        return JsonResponse({'code': 0,
                             'errmsg': 'OK',
                             'province_list': province_list})

# 子级地区：市和区县
class SubAreasView(View):
    """子级地区：市和区县"""
    def get(self, request, pk):
        """提供市或区地区数据"""
        try:
            # 1.查询市或区数据
            sub_model_list = Area.objects.filter(parent=pk)
            # 查询省份数据
            parent_model = Area.objects.get(id=pk)

            # 2.整理市或区数据
            sub_list = [{'id': i.id, 'name': i.name} for i in sub_model_list]

            sub_data = {
                'id': parent_model.id,  # pk
                'name': parent_model.name,
                'subs': sub_list
            }
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '城市或区县数据错误'})
        # 3.响应市或区数据 ok: 0
        return JsonResponse({'code': 0,
                             'errmsg': 'OK',
                             'sub_data': sub_data})

# 展示地址
class AddressView(View):
    """用户收货地址"""
    def get(self, request):
        """提供地址管理界面"""
        # 获取所有的地址
        addresses = Address.objects.filter(user=request.user,
                                         is_deleted=False)

        address_dict_list = []
        for i in addresses:
            address_dict = {
                "id": i.id,
                "title": i.title,
                "receiver": i.receiver,
                "province": i.province.name,
                "city": i.city.name,
                "district": i.district.name,
                "place": i.place,
                "mobile": i.mobile,
                "tel": i.tel,
                "email": i.email
            }
            # 将默认地址移动到[列表]最前面
            default_address = request.user.default_address # 用户默认地址
            # 将默认地址移动到[列表]最前面
            if i.id == default_address.id:
                # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'addresses': address_dict_list,
            'default_address_id': default_id
        })

# 修改地址
class UpdateDestroyAddressView(View):
    """修改和删除地址"""
    def put(self, request, address_id):
        """修改地址"""

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver') # 收货人
        province_id = json_dict.get('province_id') # 省份ID
        city_id = json_dict.get('city_id') # 城市ID
        district_id = json_dict.get('district_id') # 区县ID
        place = json_dict.get('place') # 收货地址
        mobile = json_dict.get('mobile') # 手机号
        tel = json_dict.get('tel') # 固定电话
        email = json_dict.get('email') # 邮箱

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user = request.user,
                title=receiver, # 地址标题
                receiver=receiver, # 收货人
                province_id=province_id, # 省
                city_id=city_id, # 市
                district_id=district_id, # 区
                place=place, # 详细地址
                mobile=mobile, # 手机
                tel=tel,# 固话
                email=email # 邮箱
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({
            'code':400,
            'errmsg':'更新地址成功',
            'address':address_dict
        })

    def delete(self, request, address_id):
        """删除地址"""
        try:
            address = Address.objects.get(id=address_id)
            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code': 400,
                'errmsg': '删除地址失败'
            })

        return JsonResponse({'code': 0,
                             'errmsg': '删除地址成功'})

# 设置默认地址
class DefaultAddressView(View):
    """设置默认地址"""
    def put(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '设置默认地址失败'})

        return JsonResponse({'code':0,
                                 'errmsg':'设置成功'})

# 修改地址标题
class UpdateTitleAddressView(View):
    """修改地址标题"""
    def put(self, request, address_id):
        title = json.loads(request.body.decode()).get('title')
        try:
            # 查询
            address = Address.objects.get(id=address_id)
            address.title=title
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code': 400,
                'errmsg': '设置地址标题失败'
            })
        return JsonResponse({'code': 0,
                             'errmsg': '设置地址标题成功'})

